package com.by.utils;

import com.by.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;
@Component // 注入Spring容器
public class OrderNum {
    private static final String PREFIX = "DD";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
    private static final int SEQUENCE_LENGTH = 4;
    private static final ReentrantLock LOCK = new ReentrantLock();

    // 注入 OrderMapper（替代 JdbcTemplate）
    @Autowired
    private OrderMapper orderMapper;

    public String generateOrderNo() {
        LOCK.lock();
        try {
            String dateStr = DATE_FORMAT.format(new Date());
            String orderPrefix = PREFIX + dateStr;

            // 调用 Mapper 方法查询最大订单号
            String maxOrderNo = orderMapper.selectMaxOrderNoByPrefix(orderPrefix);

            int nextSequence = calculateNextSequence(maxOrderNo, orderPrefix);
            return orderPrefix + formatSequence(nextSequence);
        } finally {
            LOCK.unlock();
        }
    }

    // 以下方法（calculateNextSequence、formatSequence）与之前相同，省略...
    private int calculateNextSequence(String maxOrderNo, String orderPrefix) {
        if (maxOrderNo == null) {
            return 1;
        }
        String sequenceStr = maxOrderNo.substring(orderPrefix.length());
        try {
            int currentSequence = Integer.parseInt(sequenceStr);
            return currentSequence + 1;
        } catch (NumberFormatException e) {
            return 1;
        }
    }

    private String formatSequence(int sequence) {
        String format = "%" + "0" + SEQUENCE_LENGTH + "d";
        return String.format(format, sequence);
    }
}
